package cn.sinjet.model.mcuupgrade;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;

import android.os.Environment;
import android.util.Log;
import cn.sinjet.carassist.SinjetApplication;
import cn.sinjet.entity.UpgradeInfo;
import cn.sinjet.utils.UpgradeUtil;

public class MCUFetchHex {
	UpgradeUtil upgrader;
	
	
	public MCUFetchHex() {
		upgrader = new UpgradeUtil(SinjetApplication.getInstance());
	}

	public void checkNewFile(final DownloadStatusCallBack downloadStatusCallBack,final String upgradePassword,final String flagName,final String fileName,final boolean checkVersion,final int fileVersion) {
		Log.d("mcu_upgrade","checkNew "+ fileName);

		new Thread(new Runnable() {
			@Override
			public void run() {
				String checkUrl;
				StringBuilder strBuilderUrl = new StringBuilder("http://120.24.64.247:8080/sinjetweb/AutoUpgrade?flag=");
				//StringBuilder strBuilderUrl = new StringBuilder("http://sinjeterp.applinzi.com/AutoUpgrade?flag=");
				strBuilderUrl.append(flagName);
				if (upgradePassword != null && upgradePassword.length() > 0)
				{
					strBuilderUrl.append("_");
					strBuilderUrl.append(upgradePassword);
				}
				checkUrl = strBuilderUrl.toString();
				
				int versionService = upgrader.getServiceMCUVersion(checkUrl);
				
				UpgradeInfo upgradeInfo = upgrader.getUpgradeInfo();
				if (upgradeInfo == null) {
					return;
				}	

				downloadStatusCallBack.downloadUpdateContent(fileName,upgradeInfo.updateContent,versionService);

				if (checkVersion)
				{
					//if (false)
					if (versionService < fileVersion)
					{
						return;						
					}
					else if (versionService == fileVersion)
					{
						downloadStatusCallBack.downloadLocalIsNew(fileName);
						return;						
					}
				}
				
				String MD5LocalFile;
				MD5LocalFile = getFileMD5(new File(Environment.getExternalStorageDirectory(),fileName));
				if (MD5LocalFile != null && MD5LocalFile.equalsIgnoreCase(upgradeInfo.md5))
				{
					return;
				}

		        try {
		        	downloadStatusCallBack.downloadServiceFileInfo(fileName,upgradeInfo.md5,upgradeInfo.downloadUrl,getFileLength(upgradeInfo.downloadUrl)); 
		        } catch (IOException e) {  
		            // TODO Auto-generated catch block  
		            e.printStackTrace();  
		        }
			}
		}).start();
	}

	public void downloadFile(final DownloadStatusCallBack downloadStatusCallBack,final String fileMD5,final String fileUrl,final String fileName) {
		Log.d("mcu_upgrade","downloadFile "+ fileUrl + fileName);

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String MD5LocalFile;
					int ret = upgrader.downloadNewMCU(fileUrl,fileName);
					if (ret == 0) {
						File file = new File(Environment.getExternalStorageDirectory(),fileName);
						MD5LocalFile = getFileMD5(file);
						if (MD5LocalFile.equalsIgnoreCase(fileMD5)) {
							Log.d("mcu_upgrade","MD5 OK ");
							downloadStatusCallBack.downloadReloadFile(fileName);
						}
						else {
							Log.d("mcu_upgrade","MD5 ERROR ");
							file.delete();
						}
					}
				}catch(Exception e) {
					e.printStackTrace();
				}

			}
		}).start();
	}

    /** 
     * 获取网络文件大小 
     * @param url 
     * @param type 
     * @return 
     * @throws IOException  
     */  
    private int getFileLength(String url1) throws IOException{  
        int length=0;  
        URL url;  
        try {  
            url = new  URL(url1);  
            HttpURLConnection   urlcon=(HttpURLConnection)url.openConnection();     
            //根据响应获取文件大小   
            length=urlcon.getContentLength();  
            urlcon.disconnect();  
        } catch (MalformedURLException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }     
        return length;  
    }  

	public static String getFileMD5(File file) {
		if (!file.isFile()) {
			return null;
		}
		byte buffer[] = new byte[4096];
		int len;
		MessageDigest digest;
		try {
			digest = MessageDigest.getInstance("MD5");
			FileInputStream in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, buffer.length)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		BigInteger bigInt = new BigInteger(1, digest.digest());
		String md5Pre = bigInt.toString(16);
		while (md5Pre.length() < 32)
		{
			md5Pre = '0' + md5Pre;
		}
		return md5Pre;
	}
}
